/**
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.solarchallenge.client.gwtui.widgets.draftapplication;

import static com.google.solarchallenge.client.rpc.ServiceProvider.getServiceProvider;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.solarchallenge.client.event.EventCategory;
import com.google.solarchallenge.client.event.HistoryHandler;
import com.google.solarchallenge.client.gwtui.mvpinterfaces.Display;
import com.google.solarchallenge.client.gwtui.mvpinterfaces.View;
import com.google.solarchallenge.client.gwtui.widgets.solarchallengeheaderbar.SolarChallengeHeaderBarDisplay;
import com.google.solarchallenge.client.gwtui.widgets.uploadonefile.UploadOneFileDisplay;
import com.google.solarchallenge.client.rpc.ServiceProvider;
import com.google.solarchallenge.shared.ApplicationDocumentCategory;
import com.google.solarchallenge.shared.ApplicationStatus;
import com.google.solarchallenge.shared.dtos.ApplicationDto;

/**
 * View for a Draft Application.
 *
 * @author Arjun Satyapal
 */
public class DraftApplicationView extends View implements
    DraftApplicationDisplay {
  @UiField
  Label labelApplicationId;
  @UiField
  UploadOneFileDisplay ufSiteDiagram;
  @UiField
  UploadOneFileDisplay ufElectricalDiagram;
  @UiField
  UploadOneFileDisplay ufDiagramNotes;
  @UiField
  Label labelOverallApplicationStatus;
  @UiField
  Label labelSiteDiagramNextStep;
  @UiField
  Label labelElectricalDiagramNextStep;
  @UiField
  Label labelDiagramNotesNextStep;
  @UiField
  Button buttonSubmit;
  @UiField
  Button buttonComeBackLater;

  private Display display;
  private String applicationId;
  private String siteDiagramUploadUrl;
  private String electricalDiagramUploadUrl;
  private String diagramNotesUploadUrl;

  private AsyncCallback<ApplicationDto> applicationDetailsCallback =
      new AsyncCallback<ApplicationDto>() {
        @Override
        public void onFailure(Throwable caught) {
          Window.alert("Failed to get Application Details from Server.");
        }

        @Override
        public void onSuccess(ApplicationDto result) {
          labelApplicationId.setText("ApplicationId = " + applicationId);
          labelSiteDiagramNextStep.setText(result.getSiteDiagramStatus().name());
          labelElectricalDiagramNextStep.setText(result.getElectricalDiagramStatus()
              .name());
          labelDiagramNotesNextStep.setText(result.getDiagramNoteStatus()
              .name());

          ApplicationStatus overAllApplStatus =
              result.getOverallApplicationStatus();
          if (overAllApplStatus == ApplicationStatus.READY_FOR_SUBMISSION) {
            buttonSubmit.setEnabled(true);
          }
          labelOverallApplicationStatus.setText(overAllApplStatus.name());
        }
      };

  private static DraftApplicationViewUiBinder uiBinder =
      GWT.create(DraftApplicationViewUiBinder.class);

  interface DraftApplicationViewUiBinder extends
      UiBinder<Widget, DraftApplicationView> {
  }

  public DraftApplicationView() {
    initWidget(uiBinder.createAndBindUi(this));

    initializeUfSiteDiagramWidget();
    this.display = this;
  }

  private void initializeUfSiteDiagramWidget() {
    ufSiteDiagram.getButtonUpload().addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent event) {
        String errorString = ufSiteDiagram.validate();

        if (errorString != null) {
          Window.alert(errorString);
        } else {
          ServiceProvider.getServiceProvider()
              .getFileUploadService()
              .getUploadUrl(null, new AsyncCallback<String>() {
                @Override
                public void onSuccess(String result) {
                  siteDiagramUploadUrl = result;
                  ufSiteDiagram.uploadToUrl(siteDiagramUploadUrl,
                      ApplicationDocumentCategory.SITE_DIAGRAM, applicationId,
                      display, applicationDetailsCallback);
                }

                @Override
                public void onFailure(Throwable caught) {
                  Window.alert("Failed to get upload URL due to reason : ["
                      + caught.getLocalizedMessage() + "].");
                }
              });
        }
      }
    });

    ufElectricalDiagram.getButtonUpload().addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent event) {
        String errorString = ufElectricalDiagram.validate();

        if (errorString != null) {
          Window.alert(errorString);
        } else {
          ServiceProvider.getServiceProvider()
              .getFileUploadService()
              .getUploadUrl(null, new AsyncCallback<String>() {
                @Override
                public void onSuccess(String result) {
                  electricalDiagramUploadUrl = result;
                  ufElectricalDiagram.uploadToUrl(electricalDiagramUploadUrl,
                      ApplicationDocumentCategory.ELECTRICAL_DIAGRAM,
                      applicationId, display, applicationDetailsCallback);
                }

                @Override
                public void onFailure(Throwable caught) {
                  Window.alert("Failed to get upload URL due to reason : ["
                      + caught.getLocalizedMessage() + "].");
                }
              });
        }
      }
    });

    ufDiagramNotes.getButtonUpload().addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent event) {
        String errorString = ufDiagramNotes.validate();

        if (errorString != null) {
          Window.alert(errorString);
        } else {
          ServiceProvider.getServiceProvider()
              .getFileUploadService()
              .getUploadUrl(null, new AsyncCallback<String>() {
                @Override
                public void onSuccess(String result) {
                  diagramNotesUploadUrl = result;
                  ufDiagramNotes.uploadToUrl(diagramNotesUploadUrl,
                      ApplicationDocumentCategory.DIAGRAM_NOTES, applicationId,
                      display, applicationDetailsCallback);
                }

                @Override
                public void onFailure(Throwable caught) {
                  Window.alert("Failed to get upload URL due to reason : ["
                      + caught.getLocalizedMessage() + "].");
                }
              });
        }
      }
    });

    buttonSubmit.addClickHandler(new ClickHandler() {

      @Override
      public void onClick(ClickEvent event) {
        getServiceProvider().getApplicantService().submitApplication(
            applicationId, new AsyncCallback<Void>() {

              @Override
              public void onSuccess(Void result) {
                Window.alert("Successfully SUBMITTED_FOR_REVIEW.");
                HistoryHandler.handleNewToken(
                    EventCategory.APPLICANT_HOME.getToken());
              }

              @Override
              public void onFailure(Throwable caught) {
                Window.alert("Failed to submit application due to : ["
                    + caught.getLocalizedMessage() + "].");
              }
            });
      }
    });

    buttonComeBackLater.addClickHandler(new ClickHandler() {

      @Override
      public void onClick(ClickEvent event) {
        Window.alert("You can visit your application from"
            + " \"Manage Applications\" under \"Applicant Home\" section.");
        HistoryHandler.handleNewToken(EventCategory.APPLICANT_HOME.getToken());
      }
    });
  }

  @Override
  public SolarChallengeHeaderBarDisplay getSolarChallengeHeaderPanel() {
    return null;
  }

  @Override
  public UploadOneFileDisplay getUfSiteDiagram() {
    return ufSiteDiagram;
  }

  @Override
  public UploadOneFileDisplay getUfElectricalDiagram() {
    return ufElectricalDiagram;
  }

  @Override
  public UploadOneFileDisplay getUfDiagramNotes() {
    return ufDiagramNotes;
  }

  @Override
  public void setEnabled(boolean enabled) {
    ufSiteDiagram.setEnabled(enabled);
    ufElectricalDiagram.setEnabled(enabled);
    ufDiagramNotes.setEnabled(enabled);
    buttonComeBackLater.setEnabled(enabled);
  }

  @Override
  public Label getLabelApplicationId() {
    return labelApplicationId;
  }

  @Override
  public String getApplicationId() {
    return applicationId;
  }

  @Override
  public Button getButtonSubmit() {
    return buttonSubmit;
  }

  @Override
  public void refreshDisplay() {
    getServiceProvider().getApplicantService().getApplicationDetails(
        applicationId, applicationDetailsCallback);
  }

  @Override
  public void setApplicationId(String applicationId) {
    this.applicationId = applicationId;
  }
}
